package site;

import constans.SizeConstans;
import database.ConnectionDB;
import database.DatabaseMysql;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

public class MapRequest extends ProcessRequest{


    private final String databaseHost;
    private final String databaseName;
    private final String databasePassword;
    private final String databaseUser;


    public MapRequest(ServletContext context){
        databaseHost      = context.getInitParameter("DatabaseHost");
        databaseName      = context.getInitParameter("DatabaseName");
        databasePassword  = context.getInitParameter("DatabasePassword");
        databaseUser      = context.getInitParameter("DatabaseUser");
    }



    @Override
    protected void process(HttpServletResponse response, String[] arguments) {

       response.setContentType("text/html; charset=\"UTF-8\"");

       PrintWriter printWriter = null;
       ConnectionDB connectionDB =null;
       DecimalFormat df = new DecimalFormat("#.#");

        try{

            printWriter=  response.getWriter();

            connectionDB =  new DatabaseMysql(databaseHost,databaseUser,databasePassword ,databaseName).getConnection();

            String query = "SELECT substring(zipcode from 1 for 5), location, sum(offeredSpace) " +
                    "FROM User, Identifier " +
                    "WHERE User.email = Identifier.email AND Identifier.lastUpdate > (SELECT DATE_SUB(curdate(), INTERVAL 1 MONTH)) " +
                    "GROUP BY substring(zipcode from 1 for 5), location;";

            ResultSet resultSet = connectionDB.executeSelect(query);

            String language = arguments[0];//Get language

            printWriter.println("<HTML>");
            printWriter.println("<HEAD>");
            printWriter.println("<META http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
            printWriter.println("<META http-equiv=\"content-language\" content=\""+language+"\">");

            if(language.equals("en")){
                printWriter.println("<META name=\"description\" content=\"Geographical location of rARC backup files.\">");
                printWriter.println("<META name=\"keywords\" content=\"rARC, map, location\">");
                printWriter.println("<TITLE>Geographical location of rARC backup files</TITLE>");
            }
            else{
                printWriter.println("<META name=\"description\" content=\"Localização das cópias de segurança do rARC.\">");
                printWriter.println("<META NAME=\"keywords\" CONTENT=\"rARC, mapa, localização\">");
                printWriter.println("<TITLE>Localização geográfica das cópias de segurança do rARC</TITLE>");
            }

            printWriter.println("<script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAmD3DSUAtswZGH9DCrDmWihSwyxmI7CPdKdH4sslZO-cSK8Ju6hTrrmcWX7Z6mvNsWGtboDJpbVvn9A&hl="+language+"\"");
            printWriter.println("type=\"text/javascript\"></script>");
            printWriter.println("<script type=\"text/javascript\">");
            printWriter.println("var geocoder;");
            printWriter.println("var map;");
            printWriter.println("function setMarker(address, space) {");
            printWriter.println("geocoder.getLatLng(address, function(point) {");
            printWriter.println("if (!point) {}");//not found
            printWriter.println("else {");
            printWriter.println("var marker = new GMarker(point);");
            printWriter.println("GEvent.addListener(marker,\"click\", function() {");
             if(language.equals("en"))
                printWriter.println("marker.openInfoWindowHtml(\"<b>Offered space</b>: \"+space+\" GB\");");
            else
                printWriter.println("marker.openInfoWindowHtml(\"<b>Espaço oferecido</b>: \"+space+\" GB\");");
            printWriter.println("});");
            printWriter.println("map.addOverlay(marker);");
            printWriter.println("}");
            printWriter.println("} ");
            printWriter.println(");");
            printWriter.println("} ");
            printWriter.println("function initialize() {");
            printWriter.println("if (GBrowserIsCompatible()) {");
            printWriter.println("map = new GMap2(document.getElementById(\"map_canvas\"));");
            printWriter.println("map.setUIToDefault();");
            printWriter.println("map.setCenter(new GLatLng(39.5, -8), 7);");
            printWriter.println("geocoder = new GClientGeocoder();");

            String zipcode;

            while(resultSet.next()){

                zipcode = resultSet.getString(1);//get zipcode
                zipcode = zipcode.trim();

                if(zipcode!=null &&  !zipcode.isEmpty())
                    zipcode = zipcode.split(" ")[0];

                printWriter.println("setMarker(\""+resultSet.getString(2)+" "+zipcode+"\",\""+df.format(resultSet.getDouble(3)/SizeConstans.GByte)+"\");");

            }

            printWriter.println("}");
            printWriter.println("}");
            printWriter.println("</script>");
            printWriter.println("<a href=\"http://www.arquivo.pt\"><img src=\"http://arquivo-web.fccn.pt/logo.jpg\" alt=\"Logotipo AWP\" border=\"0\" ></a><p>");

            if(language.equals("en")){
                printWriter.println("<CENTER><H1>Map with the geographical location of the backup files</H1></CENTER>");
                printWriter.println("<b>Beta version</b>");
            }
            else{                  
                printWriter.println("<CENTER><H1>Mapa com a distribuição geográfica das cópias de segurança</H1></CENTER>");
                printWriter.println("<b>Versão experimental</b>");
            }

            printWriter.println("<HR SIZE=1>");
            printWriter.println("</HEAD>");
            printWriter.println("<body onload=\"initialize()\" onunload=\"GUnload()\">");
            printWriter.println("<div id=\"map_canvas\" style=\"width: 1200px; height: 700px\"></div>");
            printWriter.println("</BODY>");
            printWriter.println("</HTML>");

            printWriter.flush();
            printWriter.close();

            connectionDB.closeStatement();
            connectionDB.close();

        } catch (SQLException ex) {
            Logger.getLogger(MapRequest.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (IOException ex) {
            Logger.getLogger(MapRequest.class.getName()).log(Level.WARNING, null, ex);
        } finally{
            if(printWriter!=null){
                   printWriter.close();
            }

            if(connectionDB!=null)
                try {
                connectionDB.close();
            } catch (SQLException ex) {}
        }        
    }

}
